package cc.laop.sslsocket.server;

import javax.net.ssl.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.security.KeyStore;

public class SSLSocketServer {

    private static String path = "E:\\keys\\server.jks";
    private static char[] password = "abc123".toCharArray();

    /**
     * @param args
     */
    public static void main(String[] args) {
        boolean flag = true;
        SSLContext context = null;
        try {
            KeyStore ks = KeyStore.getInstance("JKS");

            ks.load(new FileInputStream(path), password);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, password);
            KeyManager[] km = kmf.getKeyManagers();
            context = SSLContext.getInstance("SSL");
            context.init(km, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        SSLServerSocketFactory ssf = context.getServerSocketFactory();

        try {
            SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(8000);
            ss.setNeedClientAuth(false);
            ss.setWantClientAuth(false);
            System.out.println("等待客户点连接。。。");
            while (flag) {
                Socket s = ss.accept();
                BufferedInputStream is = new BufferedInputStream(s.getInputStream());
                System.out.println("接收到客户端连接");
                byte[] buffer = new byte[2048];
                int length = is.read(buffer);
                System.out.println(new String(buffer, 0, length));


                BufferedOutputStream os = new BufferedOutputStream(s.getOutputStream());
                os.write("echo : Hello".getBytes());
                os.flush();
                os.close();
                System.out.println();
                s.close();
            }
            ss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
